/**
 * 商家相关接口
 * 新增商家、删除商家、商家列表、修改商家
 */

const express = require('express')
// 引入数据库连接池
const pool = require('../../db/db')
// 引入封装后的响应结果
const Response = require('../../utils/ResponseData')
// 引入表单验证模块joi
const Joi = require('joi')

// 创建理由管理器
const router = express.Router()


/**
 * 商家查询接口
 * 请求url：http://localhost:3000/petBusiness/get
 * 请求方式： GET
 */
router.get('/petBusiness/get', async (req, res) => {
    console.log(req.query);
    // 表单校验
    // 配置校验规则
    let schema = Joi.object({
        keywords: Joi.string(),
        page: Joi.number().required(),   // 当前页码，校验规则：number型 非空
        pageSize: Joi.number().integer().max(10).required(),  // 每页显示条数，整数，最大不超过10
    })
    // 校验
    let { error, value } = schema.validate(req.query)
    if (error) {
        // 校验不通过
        res.send(Response.error(error))
        return
    }
    // 校验通过
    try {
        let { page, pageSize, keywords } = req.query
        // 根据页码和每页条数计算开始位置： 每页开始位置 = (当前页码 - 1) * 每页显示条数
        let startIndex = (page - 1) * pageSize
        pageSize = pageSize ? parseInt(pageSize) : 5

        if (!keywords) {
            keywords = ''
        }
        // 编写sql: 查询每页显示的数据
        const sql = `select * from (select * from business where b_name like ?)b1 limit ?,?`
        const result = await pool.querySync(sql, [`%${keywords}%`, startIndex, pageSize])
        // 编写sql：查询总条数
        const sql2 = `select count(b_id) as count from (select * from business where b_name like ?)b1`
        const result2 = await pool.querySync(sql2, [`%${keywords}%`])
        const total = result2[0].count
        // 获取查询到的总条数
        res.send(Response.success({
            page: parseInt(page),
            pageSize: pageSize,
            total,
            result
        }))
    } catch (e) {
        res.send(Response.error(e))
    }
})

/**
 * 商家添加接口
 * 请求url：http://localhost:3000/petBusiness/add
 * 请求方式： POST
 */
router.post('/petBusiness/add', (req, res) => {
    console.log(req.body);
    // 封装校验规则
    // 从body中解构表单数据
    let { b_img, b_name, b_price, b_JS, b_score, b_feature, b_city, b_city_detail, b_offer } = req.body
    let schema = Joi.object({
        b_img: Joi.string().required(),  // 字符串，非空
        b_name: Joi.string().required(),
        b_price: Joi.number().required(),
        b_JS: Joi.string().required(),
        b_score: Joi.number().required(),
        b_feature: Joi.string().required(),
        b_city: Joi.string().required(),
        b_city_detail: Joi.string().required(),
        b_offer: Joi.string().required()
    })
    // 校验
    let { error, value } = schema.validate(req.body)
    if (error) {
        res.send(Response.error(error))
        return
    }
    // 校验成功
    // 编写sql
    console.log('111');
    const sql = `insert into business set ?`
    // 执行sql
    pool.query(sql, { b_img, b_name, b_price, b_JS, b_score, b_feature, b_city, b_city_detail, b_offer }, (err, data) => {
        if (err) {
            res.send(Response.error('商家添加失败！'))
            return
        }
        res.send(Response.success(null, '商家添加成功'))
    })
})

/**
 * 通过ID查询商家接口
 * 请求url：http://localhost:3000/petBusiness/getById
 * 请求方式： GET 
 * 请求参数： req.query
 */
router.get('/petBusiness/getById', (req, res) => {
    // 获取前端传递的参数
    let { b_id } = req.query
    // 校验规则
    let schema = Joi.object({
        b_id: Joi.number().required()
    })
    // 校验
    let { error, value } = schema.validate(req.query)
    if (error) {
        res.send(Response.error(error))
        return
    }
    // 编写sql
    const sql = `select * from business where b_id=?`
    // 执行sql
    pool.query(sql, [b_id], (err, result) => {
        if (error) {
            res.send(Response.error('商家信息查询失败！'))
            return
        }
        if (result && result.length != 0) {
            res.send(Response.success(result[0]))
        } else {
            res.send(Response.error('未查询到相关商家！'))
        }
    })
})

/**
 * 根据id修改商家信息
 * 请求url：http://localhost:3000/petBusiness/update
 * 请求方式： POST,
 * 请求params: 表单->req.body
 */
router.post('/petBusiness/update', (req, res) => {
    // 封装校验规则
    // 从body中解构表单数据
    let { b_id, b_img, b_name, b_price, b_JS, b_score, b_feature, b_city, b_city_detail, b_offer } = req.body
    let schema = Joi.object({
        b_id: Joi.number().required(),
        b_img: Joi.string().required(),  // 字符串，非空
        b_name: Joi.string().required(),
        b_price: Joi.number().required(),
        b_JS: Joi.string().required(),
        b_score: Joi.number().required(),
        b_feature: Joi.string().required(),
        b_city: Joi.string().required(),
        b_city_detail: Joi.string().required(),
        b_offer: Joi.string().required()
    })
    // 校验
    let { error, value } = schema.validate(req.body)
    if (error) {
        res.send(Response.error(error))
        return
    }
    // 校验成功
    // 编写sql
    const sql = `update business set b_img=?, b_name=?, b_price=?, b_JS=?, b_score=?, b_feature=?, b_city=?, b_city_detail=?, b_offer=? where b_id=? `
    // 执行sql
    pool.query(sql, [b_img, b_name, b_price, b_JS, b_score, b_feature, b_city, b_city_detail, b_offer, b_id], (err, result) => {
        if (err) {
            res.send(Response.error('商家信息修改失败！'))
            return
        }
        res.send(Response.success(null, '商家信息修改成功'))
    })
})

/**
 * 根据id删除商家
 * 请求url：http://localhost:3000/petBusiness/delById
 * 请求方式： GET,
 * 请求params: 表单->req.query
 */
router.get('/petBusiness/delById', (req, res) => {
    let { b_id } = req.query
    console.log(req.query);
    let schema = Joi.object({
        b_id: Joi.number().required()
    })
    // 校验
    let { error, value } = schema.validate(req.query)
    if (error) {
        res.send(Response.error(error))
        return
    }
    // 编写sql
    const sql = `delete from business where b_id=?`
    pool.query(sql, [b_id], (err, result) => {
        if (err) {
            console.log(err);
            res.send(Response.error('商家信息删除失败！'))
            return
        }

        res.send(Response.success(null, '删除商家成功！'))
    })

})



module.exports = router